<?php

namespace app\common;

use app\model\Channel;
use app\validate\NewChannelWorker;
use Channel\Client;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Log;
use app\common\Worker;

class ProgressController  
{

    public function __construct()
    {
        $worker = new Worker();
        $worker->name = __CLASS__;

        $worker->onWorkerStart = function(){
            
            Log::debug('ProgressController 运行');
            Client::connect('127.0.0.1',Config::get('channel.channel_server_port'));

            Client::on('new_channel_worker',function(Channel $model_channel){

                $progress_name = '';

                $progress_unique_key = uniqid();


                $worker = new Worker($model_channel->listen_address);

                $worker->model = $model_channel;

                $worker->uniqid = $progress_unique_key;

                $worker->onConnect = function($connection) use($worker){

                    $connection->uniqid = uniqid();

                    $message = [
                        'connection'=>$connection
                    ];
                    Client::publish('new_channel_connent',$message);
                };

                $worker->onMessage = function($connection,$data)use($worker){
                    
                    $message = [
                        
                        'connection'=>$connection,
                        'data'=>$data
                    ];

                    Client::publish('channel_on_message',$message);

                };

                $worker->onClose = function($connection){
                    $message = [
                        'connection'=>$connection
                    ];
                    Client::publish('channel_on_close',$message);
                };

                Worker::$progressWorkerList[$progress_unique_key] = $worker;


            });
        };
        // $worker->run();

        Worker::$progressControllerWorker = $worker;
    }
}
